<?php

$base_dir =  __DIR__;

$think = $base_dir . DIRECTORY_SEPARATOR . 'think';

$cmd = $base_cmd = PHP_BINARY . ' ' . $think . ' workerman start -s httpServer';

$descriptorspec = [STDIN, STDOUT, STDOUT];
$resource = proc_open($cmd, $descriptorspec, $pipes, null, null, ['bypass_shell' => true]);

if (!$resource) {
    exit("Can not execute $cmd\r\n");
}

// 监听的文件目录
$paths = [
    $base_dir . DIRECTORY_SEPARATOR . '/app/',
    $base_dir . DIRECTORY_SEPARATOR . '/config/',
    $base_dir . DIRECTORY_SEPARATOR . '/fast/',
    
];

$files = [
    $base_dir . DIRECTORY_SEPARATOR . '/.env',
];

// 当前启动的时间
$lastMtime = time();
while (1) {
    sleep(2);
    foreach($files as $file) {
        $info = new SplFileInfo($file);
        if ($lastMtime < $info->getMTime()) {
            $lastMtime = $info->getMTime();

            $status = proc_get_status($resource);
            $pid = $status['pid'];
            shell_exec("taskkill /F /T /PID $pid");
            $resource = proc_open($cmd, $descriptorspec, $pipes, null, null, ['bypass_shell' => true]);;
            break;
        }
    }
    foreach ($paths as $path) {
        $dir      = new RecursiveDirectoryIterator($path);
        $iterator = new RecursiveIteratorIterator($dir);

        foreach ($iterator as $file) {
            if (pathinfo($file, PATHINFO_EXTENSION) != 'php') {
                continue;
            }

            // 文件的修改时间
            if ($lastMtime < $file->getMTime()) {
                echo '[update]' . $file . "\n";
                $lastMtime = $file->getMTime();

                $status = proc_get_status($resource);
                $pid = $status['pid'];
                shell_exec("taskkill /F /T /PID $pid");
                $resource = proc_open($cmd, $descriptorspec, $pipes, null, null, ['bypass_shell' => true]);;
                break 2;
            }
        }
    }
}
